<template>
  <div class="container">
    <el-form
      :model="formData"
      label-width="120px"
      style="width: 800px"
      :rules="rules"
      ref="formRef"
      hide-required-asterisk
    >
      <!-- 第一行：姓名和性别 -->
      <el-row class="row1 form-row">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="formData.studentName" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <!-- 第二行：电话和账号 -->
      <el-row class="form-row">
        <el-form-item label="电话" prop="tel">
          <el-input v-model="formData.tel" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formData.account" disabled></el-input>
        </el-form-item>
      </el-row>
      <!-- 第三行：密码 -->
      <el-row class="form-row">
        <el-form-item label="紧急联系人">
          <el-input v-model="formData.emContact" placeholder="请输入紧急联系人"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系人电话" prop="emTel">
          <el-input v-model="formData.emTel" placeholder="请输入紧急联系人电话"></el-input>
        </el-form-item>
      </el-row>
      <el-row class="form-row">
        <el-form-item label="家庭住址">
          <el-input v-model="formData.address" placeholder="请输入家庭地址"></el-input>
        </el-form-item>
        <el-form-item label="班级名称">
          <el-input v-model="formData.className" disabled></el-input>
        </el-form-item>
      </el-row>
      <el-row class="form-row">
        <el-form-item label="学校和专业" prop="major">
          <el-input v-model="formData.major"></el-input>
        </el-form-item>
        <el-form-item label='密码' prop="password">
          <el-input v-model="formData.password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-row>
      <!-- 第四行：修改按钮居中 -->
      <el-row class="form-row">
        <el-button type="primary" @click="handleModify">修改</el-button>
      </el-row>
    </el-form>
  </div>
</template>
  
  <script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getmsg ,updateMsg} from '../api/SInformation'

// 本地存储
const user = JSON.parse(localStorage.getItem('user'))

const formData = ref({})

const flag = ref(false)
const oldformData = ref({})
// 根据用户 id 获取用户信息
function getUserInfoById() {
  let data = {
    userId: user.userId,
  }
  getmsg('StuByUserId', data).then((res) => {
    if (res.code == 200) {
      formData.value = res.dataset
      oldformData.value = JSON.parse(JSON.stringify(res.dataset));
      formData.value.password = ''
    }
  })
}
onMounted(() => {
  getUserInfoById()
})

// 修改信息
function handleModify1() {
  let data = {
    studentId: formData.value.studentId,
    studentName: formData.value.studentName,
    sex: formData.value.sex,
    classId: formData.value.classId,
    className: formData.value.className,
    account: formData.value.account,
    address: formData.value.address,
    emContact: formData.value.emContact,
    emTel: formData.value.emTel,
    major: formData.value.major,
  }
  if(formData.value.tel!=oldformData.value.tel){
    data.tel = formData.value.tel
    flag.value = true
  }
  if (formData.value.password) {
    data.password = formData.value.password
    flag.value = true
  }
  updateMsg('updateStudent', data).then((res) => {
    if (res.code == 200) {
      ElMessage.success('修改成功')
      getUserInfoById()
    }else{
      ElMessage.error('修改失败')
    }
  })
}
const formRef = ref(null)
const handleModify = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let msg=''
      if(formData.value.tel!=oldformData.value.tel){
        msg='是否修改信息？,手机号已修改，账号更新为：stu_'+formData.value.tel+'，密码已重置为123456'
      }else{
        msg='是否修改信息？'
      }
     
      ElMessageBox.confirm(`${msg}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          handleModify1()
          if(flag.value){
            //清除本地index
            sessionStorage.removeItem('activeIndex')
            //跳转到登录页面
            setTimeout(() => {
              window.location.href = '/'
            }, 1000)
          }
        })
        .catch(() => {
          ElMessage.info('已取消修改')
        })
    }
  })
}
// 表单验证规则
const rules = {
  studentName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  tel: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  major: [
    { required: true, message: '学校和专业不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '学校和专业长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  password: [
    { 
      validator: (rule, value, callback) => {
        if (value && (value.length < 5 || value.length > 20)) {
          callback(new Error('密码长度需在5-20位之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur' 
    }
  ],
  emTel: [
    { 
      validator: (rule, value, callback) => {
        if (value && !/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      trigger:  'blur'
    }
  ],
}
</script>
  
  <style scoped>
/* 可以根据需要添加更多样式 */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.el-form {
  width: 800px;
  background-color: #fff;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
}
.el-row {
  margin-bottom: 20px;
}
button {
  background-color: #0f6ab1;
}
button:hover {
  background-color: #07509e;
}
.row1 {
  margin-top: 20px;
}
.el-select {
  width: 200px;
}
/* 自定义表单行样式 */
.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 两列布局 */
  justify-items: center; /* 表单项水平居中 */
}

/* 第四行按钮样式，单独处理 */
.form-row:last-child {
  display: flex;
  justify-content: center;
  grid-template-columns: none; /* 移除网格布局 */
}
/* 表单项样式 */
.el-form-item {
  margin-bottom: 0;
}
</style>